package com.sf.dlb.service;

import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.jpa.model.WalletAddressInfo;
import com.sf.dlb.jpa.repository.NewClassRepository;
import com.sf.dlb.jpa.repository.WalletAddressRepository;
import com.sf.dlb.config.Global;
import com.sf.dlb.utils.GsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created by jing.tan on 2018/5/21.
 */
@Service
public class WalletAddressService {
    private static Logger logger = LoggerFactory.getLogger(WalletAddressService.class);
    @Autowired
    private NewClassRepository newClassRepository;
    @Autowired
    private WalletAddressRepository walletAddressRepository;
    @Resource
    private Global global;

    /**
     * 设置默认地址
     * @return
     */
    public WalletAddressInfo setDafaultAddress(String userId,String extractAddress){
        logger.info("setDafaultAddress start userId={}, extractAddress={}",userId,extractAddress);
        if(StringUtils.isEmpty(userId)||StringUtils.isEmpty(extractAddress)){
            logger.info("setDafaultAddress userId&extractAddress is null");
            return null;
        }
        //取消其他默认地址
        List<WalletAddressInfo> walletAddressInfos=walletAddressRepository.findByUserIdAndDelFlag(userId,"0");
        for (WalletAddressInfo walletAddressInfo:walletAddressInfos) {
            if(walletAddressInfo.getDefaultState().equals(ResponseConstant.extract_address_default)){
                walletAddressInfo.setDefaultState(ResponseConstant.extract_address_not_default);
                walletAddressInfo.setUpdateDate(new Date());
                walletAddressRepository.save(walletAddressInfo);
            }
        }
        //判断地址是否存在
        WalletAddressInfo walletAddressInfo = walletAddressRepository.findByAddressAndDelFlag(extractAddress.trim(),"0");
        if(null==walletAddressInfo){
            walletAddressInfo=new WalletAddressInfo();
            walletAddressInfo.setUserId(userId);
            walletAddressInfo.setAddress(extractAddress);
            walletAddressInfo.setDefaultState(ResponseConstant.extract_address_default);
            walletAddressInfo.setCreateDate(new Date());
            walletAddressInfo.setUpdateDate(new Date());
        }else{
            walletAddressInfo.setDefaultState(ResponseConstant.extract_address_default);
            walletAddressInfo.setUpdateDate(new Date());
        }
        walletAddressInfo=walletAddressRepository.save(walletAddressInfo);
        logger.info("setDafaultAddress end walletAddressInfo={}", GsonUtils.getInstance().toJson(walletAddressInfo));
        return walletAddressInfo;
    }
}
